import Vue from "vue";
import Vuex from "vuex";
import dynamicRoutes from "../router/dynamicRoutes"
import allRoutes from "../router/allRoutes"
import recursionRoutes from "../utils/recuisionRoutes"
import * as api from "@/api"
import router from "../router"

Vue.use(Vuex);
let userInfo = localStorage.getItem('lp-userInfo') || "{}";
let userButtons = localStorage.getItem("lp-userbutton") || "[]"
    //刷新页面 mutations没有人调用
export default new Vuex.Store({
    state: {
        userInfo: JSON.parse(userInfo), //用户信息
        sideMenu: [], //用户的侧边栏菜单
        menuFlag: false, //菜单栏缩进
        crubms: [], //面包屑数据
        userButtons: JSON.parse(userButtons), //权限按钮
    },
    mutations: {
        /* 用户权限 */
        SET_USERBUTTONS(state, payload) {
            state.userButtons = payload
        },
        /* 菜单缩进 */
        SET_MENUFLAG(state) {
            state.menuFlag = !state.menuFlag
        },
        /* 面包屑 */
        SET_CRUBMS(state, payload) {
            state.crubms = payload
                /* console.log(state.crubms); */
        },
        SET_USERINFO(state, payload) {

            state.userInfo = payload
                /*  console.log(state.userInfo); */
        },
        /* 用户侧边栏 信息 */
        SET_SIDE_MENU(state, payload) {
            state.sideMenu = payload
                /*  console.log(state.sideMenu); */
                //在dy中找到home路由 把所有的路由添加到它的children中
            let target = dynamicRoutes.find(item => item.path === "/")
            target.children = [...payload]
            router.addRoutes(dynamicRoutes) //将计算好的路由发送到 index里面
        }
    },
    actions: {
        //发起异步请求获取用户菜单
        FETCH_MENU_LIST({ commit }) {
            return api.getMenuListApi()
                .then(res => {

                    let menuList = res.data.menuList
                        //递归得出用户菜单
                    let userMenu = recursionRoutes(allRoutes, menuList)
                    commit("SET_SIDE_MENU", userMenu)
                })
        }
    },
    modules: {},
});